var fs = require('fs')
// 接口数据
var Animes = require('../service/anime')
var Games = require('../service/game')
var Musics = require('../service/music')
var News = require('../service/new')
var Users = require('../service/user')
// Express 提供了一种更好的方式
// 专门用来包装路由的
var express = require('express')

// 1. 创建一个路由容器
var router = express.Router()

var getIp = require('ipware')().get_ip;

// 2. 把路由都挂载到 router 路由容器中


/*
 * 设置数据接口 （接口）
 */
router.get('/moongoDB/animes', function (req, res) {
  Animes.find(function (err, animes) {
    if (err) {
      return res.status(500).send('Server error')
    }
    animes = JSON.stringify(animes);
    animes = JSON.parse(animes);
    // res.render('node.html',{animes: animes});
    res.send(animes);
  })
})

router.get('/moongoDB/games', function (req, res) {
  Games.find(function (err, games) {
    if (err) {
      return res.status(500).send('Server error')
    }
    games = JSON.stringify(games);
    games = JSON.parse(games);
    // res.render('node.html',{animes: animes});
    res.send(games);
  })
})

router.get('/moongoDB/musics', function (req, res) {
  Musics.find(function (err, musics) {
    if (err) {
      return res.status(500).send('Server error')
    }
    musics = JSON.stringify(musics);
    musics = JSON.parse(musics);
    // res.render('node.html',{animes: animes});
    res.send(musics);
  })
})
router.get('/moongoDB/news', function (req, res) {
  News.find(function (err, news) {
    if (err) {
      return res.status(500).send('Server error')
    }
    news = JSON.stringify(news);
    news = JSON.parse(news);
    // res.render('node.html',{animes: animes});
    res.send(news);
  })
})


// 注册用户
router.post('/moongoDB/register', function (req, res) {
  Users.find(function (err, users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);

    var date = new Date();
    req.body.uid = users[users.length - 1].uid + 1;
    req.body.time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`;
    req.body.exp = 0;
    req.body.adminKey = '';
    req.body.lastLogin = '从未登录';
    req.body.clientIp = getIp(req).clientIp;
    req.body.innerIp = '';
    req.body.address = '';
    req.body.online = '离线';
    req.body.userType = 0;
    req.body.imgSrc = "../public/img/index/tx/tx.jpg";
    new Users(req.body).save(function (err) {
      if (err) {
        console.log(err);
        return res.status(500).send('Server error.')
      } else {
        res.send('注册成功，请先登录哦')
      }
    })
  })
})

// 检查昵称
router.post('/moongoDB/checkName', function (req, res) {
  Users.find(function (err, users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);

    var username = req.body.username;
    var name = req.body.name;
    if (users.filter(item => item.name == name).length != 0) res.send({ state: 1, des: '该昵称已被他人使用' });
    else if (users.filter(item => item.username == username).length != 0) res.send({ state: 1, des: '该手机号已被注册了哦' });
    else res.send({ state: 0, des: '' });

  })
})

// 检查登陆
router.post('/moongoDB/checkLogin', function (req, res) {
  Users.find(function (err, users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);

    var username = req.body.username;
    var password = req.body.password;
    var user = users.filter(item => item.username == username);

    if (user.length == 0) return res.send({ state: 1, des: '该手机号未注册哦' });
    if (password != user[0].password) return res.send({ state: 1, des: '密码不正确哦' });
    else res.send({ state: 0, des: `欢迎您，${user[0].name}登录成功哦`, obj: user[0] });

  })
})

// 每日登陆
router.post('/moongoDB/loginInit', function (req, res) {
  var id = req.body._id.replace(/"/g, '');
  var clientIp = req.body.clientIp;
  var lastLogin = req.body.lastLogin;
  var address = req.body.address;
  var innerIp = req.body.innerIp;
  Users.findById(id, function (err, users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);
    var noticeSwitch = false;
    if (users.lastLogin.split(' ')[0] != lastLogin.split(' ')[0]) {
      users.exp = users.exp + 5;
      noticeSwitch = true;
    };
    users.lastLogin = lastLogin;
    users.clientIp = clientIp;
    users.address = address;
    users.innerIp = innerIp;
    if (users.exp >= 99999) users.exp = 99999;
    Users.findByIdAndUpdate(id, users, function (err) {
      if (err) {
        return res.status(500).send('Server error')
      }
      else {
        if (noticeSwitch) res.send({text:'每日登陆+5EXP!',exp:users.exp})
        else res.send();
      }
    })
  })
})
// 密码昵称手机号
router.post('/moongoDB/editUserInfo', function (req, res) {
  var id = req.body._id.replace(/"/g, '');
  var name = req.body.name;
  var password = req.body.password;
  var username = req.body.username;
  var editNum = req.body.editNum;
  var exp = req.body.exp;
  var editType = req.body.editType;
  var text = {};var users = {};
  if(editType==1){
    if (editNum == 1) {
      users.name = name; text.text = '修改昵称成功';
      users.exp = exp - 1; text.name = name; text.exp = users.exp;
      if (users.exp < 0) return res.send('经验不足，昵称改不了哦');
    };
    if (editNum == 2) {
      users.password = password;
      text.text = '修改密码成功';
      text.password = password;
    };
  }else if(editType==2){
    users.username = username;
    text.text = '修改手机号成功';
    text.username = username;
  }
  users = JSON.parse(JSON.stringify(users));
  Users.findByIdAndUpdate(id, users, function (err) {
    if (err) {
      return res.status(500).send('Server error')
    }
    else {
      res.send(text);
    }
  })
})
// 改头换面
router.post('/moongoDB/changeTx', function (req, res) {
  var id = req.body._id.replace(/"/g, '');
  var imgSrc = req.body.imgSrc;
  var text = '更换头像成功'
  Users.findByIdAndUpdate(id, req.body, function (err) {
    if (err) {
      return res.status(500).send('Server error')
    }
    else {
      res.send(text);
    }
  })
})

// 在线人头/离线
router.post('/moongoDB/getUsers',function (req,res){
  var online = req.body.online;
  Users.find(function (err,users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);
    var onlineUsers = [];
    var onlineArr = users.filter(item=>{
        onlineUsers.push({
          name:item.name,imgSrc:item.imgSrc,
          _id:item._id,exp:item.exp,
          clientIp:item.clientIp,innerIp:item.innerIp,
          userType:item.userType,uid:item.uid,
          username:item.username,time:item.time,
          lastLogin:item.lastLogin,address:item.address,
          online:item.online
        });
        return item.online == '在线';
    });
    if(onlineArr.length==0) return res.send({state:'info',des:'没人在线哦'});
    res.send({state:'success',des:'获取人数成功',onlineUsers:onlineUsers});
  })
})

// 获取对应的额历史记录
router.post('/moongoDB/getChat',function (req,res){
  var id = req.body.id.replace(/"/g, '');
  var toId = req.body.toId.replace(/"/g, '');
  Users.findById(id,function (err,users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);
    var thisIndex;
    var chatMessage = users.chatMessage.filter((item,index)=>{if(item._id==toId){thisIndex=index;return item._id==toId;}})[0];
    if(!chatMessage) return res.send({state:'info',des:'没有相关的历史记录'});
    chatMessage.history.map(msg=>{if(msg.read==0) msg.read=1});
    
    
    users.chatMessage.splice(thisIndex,1);
    users.chatMessage.push(chatMessage);
    res.send({state:'success',des:'获取历史记录成功',chatMessage:chatMessage});
    Users.findByIdAndUpdate(id,users,function(err){
      if(err) console.log(err);
    })
  })
})

// 获取全部历史记录
router.post('/moongoDB/getMessage',function (req,res){
  var id = req.body.id.replace(/"/g, '');
  Users.findById(id,function (err,users) {
    if (err) {
      return res.status(500).send('Server error')
    }
    users = JSON.stringify(users);
    users = JSON.parse(users);
    var chatMessage = users.chatMessage;
    res.send({state:'success',des:'获取全部历史记录成功',chatMessage:chatMessage});
  })
})

// 补零
function addZero(num) {
  if (num < 10) return `0${num}`;
  else return num;
}


// 3. 把 router 导出
module.exports = router